package com.zgkxzx.java.mutilThread.myAtomVar;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 创建者 zgkxzx
 * 日期   1/4/18
 * 描述
 */

public class MyAtomVariable extends AtomicInteger {

    private int maxNumber = 0;

    public MyAtomVariable(int maxNumber) {
        set(0);
        this.maxNumber = maxNumber;
    }


    public boolean carIn() {
        for (; ; ) {
            int value = get();
            if (value == maxNumber) {
                System.out.println("had over max");
                return false;
            } else {
                int newValue = value + 1;
                boolean b = compareAndSet(value, newValue);
                if (b) {
                    System.out.println("had enter");
                    return true;
                }

            }


        }
    }

    public boolean carOut() {
        for (; ; ) {
            int value = get();
            if (value == 0) {
                System.out.println("had over 0");
                return false;
            } else {
                int newValue = value - 1;
                boolean b = compareAndSet(value, newValue);
                if (b) {
                    System.out.println("had enter11");
                    return true;
                }
            }
        }
    }

}
